<?php

namespace App\Jobs\Zhunya;

use App\Models\CacheModel\acquired_astro\AppAcquiredAstroTestRecord;
use App\Models\CacheModel\acquired_astro\ZhunleappAstroExercise;
use App\Tools\Service\ChatParse;

use Illuminate\Bus\Queueable;
use Illuminate\Queue\SerializesModels;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;

class AcquiredAstroJob implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    public $jobData;

    /**
     * Create a new job instance.
     *
     * @param array $jobData
     */
    public function __construct(array $jobData)
    {
        $this->jobData = $jobData;
    }

    /**
     * Execute the job.
     *
     * @return void
     */
    public function testCalculate()
    {
      $jobData = $this->jobData;
        // $jobData = [
        //     'id' => 1,  // 测试记录ID   app_acquired_astro_test_record表ID
        //     'force' => false,   // 是否强制重新计算
        // ];
        $force = $jobData['force'] ?? false;
        $acquiredAstroTestRecordModel = new AppAcquiredAstroTestRecord();
        $zhunleappAstroExerciseModel = new ZhunleappAstroExercise();
        $testAnswerDataInfo = $acquiredAstroTestRecordModel->getInfoById($jobData['id']);
        if (!$force && $testAnswerDataInfo['status'] === 3)
        {   //  计算完成 并不强制重新计算
            $job->delete();
            return;
        }
        try
        {
            $nowTime = time();
            if ($testAnswerDataInfo['status'] !== 2)
            {   // 状态不是计算中 更新至计算中
                $acquiredAstroTestRecordModel->updateData($jobData['id'], $testAnswerDataInfo['uid'], ['status' => 2, 'start_time' => $nowTime, 'update_time' => $nowTime]);
            }
            $answerData = $testAnswerDataInfo['answer_data'];
            $questionList = $zhunleappAstroExerciseModel->batchGetInfoByIds(array_merge($answerData['q1'], $answerData['q2'], $answerData['q3'], $answerData['q4'], $answerData['q5']), ['id', 'a_type', 'b_type']);
            $categoryData = $zhunleappAstroExerciseModel::getQuestionCategoryData();
            $data = [];
            $seniorTestLetter = [];
            $resD = [1 => 0, 2 => 0, 3 => 0, 4 => 0, 5 => 0, 6 => 0, 7 => 0, 8 => 0,];
            foreach ($categoryData as $cid => $cname)
            {
                if ($answerData['q' . $cid . '_num'] <= 0)
                {
                    continue;
                }
                $item = [1 => 0, 2 => 0, 3 => 0, 4 => 0, 5 => 0, 6 => 0, 7 => 0, 8 => 0,];
                foreach ($answerData['q' . $cid] as $qid)
                {
                    if (!isset($answerData['answer'][$qid]))
                    {
                        continue;
                    }
                    $answerItem = $answerData['answer'][$qid];
                    if ($answerItem[0] === 'A')
                    {   // 答案选择 A
                        $item[$questionList[$qid]['a_type']]++;
                    } else
                    {   // 答案选择 B
                        $item[$questionList[$qid]['b_type']]++;
                    }
                }
                $type = $acquiredAstroTestRecordModel->getResultTypeByAnswer($item);
                $data[] = [
                    'type' => $type,
                    'data' => $item,
                ];
                $seniorTestLetter[] = $type;
                $resD[1] += $item[1];
                $resD[2] += $item[2];
                $resD[3] += $item[3];
                $resD[4] += $item[4];
                $resD[5] += $item[5];
                $resD[6] += $item[6];
                $resD[7] += $item[7];
                $resD[8] += $item[8];
            }
            $resType = $acquiredAstroTestRecordModel->getResultTypeByAnswer($resD);
            $answerLst = [];
            foreach ($answerData['answer'] as $qid => $answer)
            {
                $answerLst[] = [
                    'id' => $qid,
                    'option' => $answer[0],
                ];
            }
            $chatParams = [
                'uid' => $testAnswerDataInfo['uid'],
                'type' => $testAnswerDataInfo['type'] === 1 ? 0 : 1,   // 0==>基础测试  1==>专业测试
                'answer_lst' => $answerLst, // [{"id":15,'option':"A"},]  type=0 时，列表内是基础题库的20道答案 【列表长度20】， type=1 时，列表内是所有题库的20道答案 【列表长度100】
                'base_test_letter' => $resType,   // 示例："PAED"   type = 0 时，传入此值
                'senior_test_letter' => $seniorTestLetter, // 示例：["PAED"，"PAED","PAED","PAED","PAED"] 第一个位置是综合类, 第二个位置是恋爱题库,第三个位置是财富题库,第四个位置是工作题库, 第五个位置是人际类
            ];
            $calculateData = ChatParse::getAcquiredAstroCalculateData($chatParams);
            if ($calculateData['success'] && $calculateData['data']['code'] === 200)
            {   // 计算成功
                $resCalculateData = $calculateData['data'];
                unset($resCalculateData['code']);
                $resCalculateData['res_type'] = $resType;
                $resCalculateData['res_answer_data'] = $data;
                // 更新 计算结果
                $acquiredAstroTestRecordModel->updateData($jobData['id'], $testAnswerDataInfo['uid'], [
                    'status' => 3,  // 0=>待测试 1=>测试完成等待计算 2=>计算中 3=>计算完成 4=>计算失败
                    'content' => $resCalculateData, // 计算结果
                    'suc_time' => $nowTime, // 计算成功时间
                    'update_time' => $nowTime,
                ]);
            } else
            {   // 计算失败
                $acquiredAstroTestRecordModel->updateData($jobData['id'], $testAnswerDataInfo['uid'], [
                    'status' => 4,  // 0=>待测试 1=>测试完成等待计算 2=>计算中 3=>计算完成 4=>计算失败
                    'content' => $calculateData,
                    'update_time' => $nowTime,
                ]);
            }
        }
        catch (\Exception $e)
        {
            \think\Log::write(__CLASS__ . ' => ' . __FUNCTION__ . '() *** 后天星座计算 *** 异常：' . $e->getMessage() . '失败信息：' . $e->getFile() . ':' . $e->getLine(), 'error', true);
        }
       // $job->delete();
    }
}